from django.core.paginator import Paginator
from rest_framework import viewsets, mixins
from rest_framework.decorators import action, api_view
from rest_framework.response import Response
from goods.models import SKU, SKUSpecification, GoodsCategory
from goods.serlailzer import SKUSerializer


class Sku(viewsets.GenericViewSet, mixins.RetrieveModelMixin):

    queryset = SKU.objects.all()
    serializer_class = SKUSerializer

    def retrieve(self, request, *args, **kwargs):
        sku = SKU.objects.filter(id=kwargs['pk']).first()
        skuspecs = SKUSpecification.objects.filter(sku_id=kwargs['pk'])
        sku = skuspecs.first().sku
        specs = []
        for i in skuspecs:
            skuspec = i.spec
            option1 = i.option
            dict2 = {}
            dict2['sku_id'] = i.sku_id
            dict2['value'] = option1.value
            dict1={}
            dict1['name'] = skuspec.name
            dict1['options'] = []
            dict1['options'].append(dict2)
            specs.append(dict1)
        res = {
                'code': 200,
                'data': {'sku': self.get_serializer(sku).data,
                         'specs': specs
                         }
               }
        return Response(res)


class Sku_categories(viewsets.GenericViewSet,
                     mixins.ListModelMixin):

    queryset = GoodsCategory.objects.all()

    def list(self, request, *args, **kwargs):
        instance = self.get_queryset().filter(id=request.query_params['category_id']).first()
        # serializer = self.get_se(instance)
        cat1 = instance.name
        category_name = instance.parent.name
        res = {'data': {'cat1': {'url': '', 'category_name': category_name}, 'cat2': cat1}}
        return Response(res)


@api_view(['GET'])
def skus(request, id):
    page_size = request.query_params.get('page_size')
    page1 = request.query_params.get('page')
    ordering = request.query_params.get('ordering')
    skus = SKU.objects.filter(category_id=id).order_by(ordering)
    count = len(skus)
    p = Paginator(skus, page_size) # p 分的的页数   page_size：每页的个数
    data1 = p.page(page1) # data1是一页的内容  page1是具体的某一页
    results = SKUSerializer(data1, many=True).data
    res = {'data': {'count': count, 'results': results}}
    return Response(res)


@api_view(['GET'])
def skusall(request):
    skus = SKU.objects.all()
    count = len(skus)
    results = SKUSerializer(skus, many=True).data
    res = {'data': {'count': count, 'results': results}}
    return Response(res)


